<template>
  <el-container class="tabLibrary-container">
    <!-- 搜索区域 -->
    <el-header>
      <div class="tabLibrary-search">
        <span style="padding-right: 10px;">标签名称：</span>
        <!-- 绑定-刷新-重置 -->
        <el-input size="small" placeholder="请输入标签名称" v-model="queryInfo.labelName" @keyup.enter.native="getTabList" clearable @clear="getTabList">
          <el-button size="small" slot="append" icon="el-icon-search" @click="getTabList()"></el-button>
        </el-input>
      </div>
    </el-header>

    <!-- 列表区域 -->
    <el-main>
      <div style="padding-bottom: 10px;">
        <el-button size="small" type="primary" @click="showAddTabDialog"><i class="el-icon-plus"></i>&nbsp;新增</el-button>
      </div>

      <!-- 标签数据 -->
      <el-table :data="tabList" :header-cell-style="rowClass" style="width: 100%">
        <!-- 标签名称，知识类别，标签颜色，排序，备注，创建人，创建时间 -->
        <el-table-column prop="labelName" label="标签名称">
        </el-table-column>
        <el-table-column prop="knowCateName" label="知识类别">
        </el-table-column>
        <el-table-column prop="labelColor" label="标签颜色">
          <template slot-scope="scope">
            <span>{{ scope.row.labelColor }}</span>
            <span :style="{color: scope.row.labelColor}"><i class="el-icon-s-flag" ></i> </span>
          </template>
        </el-table-column>
        <el-table-column prop="labelSort" label="排序">
        </el-table-column>
        <el-table-column prop="notes" label="备注">
        </el-table-column>
        <el-table-column prop="staffName" label="创建人">
        </el-table-column>
        <el-table-column prop="createtime" label="创建时间">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain icon="el-icon-edit"
            @click="showEditTabDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain icon="el-icon-delete"
            @click="removeTabByID(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <div style="padding-top: 10px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum" :page-sizes="[5, 10, 20]" :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>

      <!-- 新增标签的对话框 -->
      <el-dialog title="新增标签" :visible.sync="addTabDialogVisible" width="30%">
        <el-form :model="addTabForm" :rules="addTabFormRules" ref="addTabForm" label-width="auto">
          <el-form-item label="知识类别" prop="knowCateId">
            <el-select v-model="addTabForm.knowCateId" placeholder="请选择" filterable>
              <el-option v-for="item in knowCateForm" :key="item.knowCateId"
                :label="`${item.cateId}_${item.knowCateName}`" :value="item.knowCateId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签名" prop="labelName">
            <el-input v-model="addTabForm.labelName" clearable></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="labelSort">
            <el-input v-model="addTabForm.labelSort" clearable></el-input>
          </el-form-item>
          <el-form-item label="标签颜色" prop="labelColor">
              <el-color-picker v-model="addTabForm.labelColor"></el-color-picker>
          </el-form-item>
          <el-form-item label="备注" prop="notes">
            <el-input v-model="addTabForm.notes" clearable></el-input>
          </el-form-item>
          
          <!-- 创建人是否直接引入用户名 -->
          <el-form-item label="创建人" prop="staffCode">
            <el-input v-model="addTabForm.staffCode" :readonly="true"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addTabDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addTab">确 定</el-button>
        </span>
      </el-dialog>
      
      <!-- 编辑标签的对话框 -->
      <el-dialog title="编辑标签" :visible.sync="editTabDialogVisible" width="30%">
        <el-form :model="editTabForm" :rules="addTabFormRules" ref="editTabForm" label-width="auto">
          <el-form-item label="知识类别">
            <el-select v-model="editTabForm.knowCateId" placeholder="请选择" filterable disabled>
              <el-option v-for="item in knowCateForm" :key="item.knowCateId"
                :label="`${item.cateId}_${item.knowCateName}`" :value="item.knowCateId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签名" prop="labelName">
            <el-input v-model="editTabForm.labelName" clearable></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="labelSort">
            <el-input v-model="editTabForm.labelSort" clearable></el-input>
          </el-form-item>
          <el-form-item label="标签颜色" prop="labelColor">
              <el-color-picker v-model="editTabForm.labelColor"></el-color-picker>
          </el-form-item>
          <el-form-item label="备注" prop="notes">
            <el-input v-model="editTabForm.notes" clearable></el-input>
          </el-form-item>
          
          <!-- 创建人是否直接引入用户名 -->
          <el-form-item label="创建人" prop="staffCode">
            <el-input v-model="editTabForm.staffCode" :readonly="true"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editTabDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editTab">确 定</el-button>
        </span>
      </el-dialog>

    </el-main>
  </el-container>
</template>

<script>
import { getAllLableApi, tabInsertApi, tabUpdateApi,tabDeleteByIDApi } from '@/api/manageApi'
import { getKnowCategoryApi } from '@/api/reportApi'


export default {
  data() {
    return {
      tabList: [],
      // 查询条件
      queryInfo: {
        pageNum: 1, //页码
        pageSize: 10, //每页显示多少条数据
      },
      total: 0,

      // 调用接口数据
      knowCateForm: [],

      //todo 新增标签
      addTabDialogVisible: false,
      addTabForm: {
        knowCateId: '',
        labelName: '',
        labelSort: '',
        labelColor: '',
        notes: '',
      },
      addTabFormRules: {
        knowCateId: [
          { required: true, message: '请选择知识类别', trigger: 'change' }
        ],
        labelName: [
          { required: true, message: '请输入标签名', trigger: 'blur' }
        ],
        labelSort: [
          { required: true, message: '请输入标签序号', trigger: 'blur' }
        ],
        labelColor: [
          { required: true, message: '请输入标签颜色', trigger: 'blur' }
        ],
      },

      // todo 编辑标签
      editTabDialogVisible: false,
      editTabForm: {},
    }
  },
  created() {
    this.getTabList()
    this.getKnowCategory()
  },
  methods: {
    //设置表头的颜色
    rowClass({ row, rowIndex }) {
      return 'background:#f5f7fd'
    },
    // 标签查询
    async getTabList() {
      const { data: res } = await getAllLableApi(this.queryInfo);
      // console.log("查询成功");
      this.tabList = res.list.records;
      this.total = res.list.total;
    },
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getTabList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getTabList();
    },

    //todo 新增标签
    async getKnowCategory() {
      const { data: res } = await getKnowCategoryApi();
      this.knowCateForm = res.list;
    },
    showAddTabDialog() {
      this.addTabDialogVisible = true;
      // ! 创建者暂时设置一个默认值，后续和用户模块绑定
      this.addTabForm.staffCode = '0001';
      if (this.$refs.addTabForm !== undefined) {
        this.$refs.addTabForm.resetFields();
        this.addTabForm.knowCateId = '';
      }
    },
    async addTab() {
      this.$refs.addTabForm.validate(async (valid, field) => {
        if (!valid) {
          let arr = Object.keys(field)
          return this.$message.error({
            message: field[arr[0]][0].message,
            druation: 1500
          })
        }
        console.log('验证通过');

        const { data: res } = await tabInsertApi(this.addTabForm);
        console.log("新增成功");
        this.addTabDialogVisible = false;
        this.getTabList();
      })
    },

    //todo 编辑分类
    async showEditTabDialog(cateInfo) {
      // 用JSON进行深拷贝，防止未请求就修改数据
      this.editTabForm = JSON.parse(JSON.stringify(cateInfo));
      this.editTabDialogVisible = true;
      if (this.$refs.editTabForm !== undefined) {
        this.$refs.editTabForm.resetFields();
      }
    },

    async editTab() {
      this.$refs.editTabForm.validate(async (valid, field) => {
        if (!valid) {
          let arr = Object.keys(field)
          return this.$message.error({
            message: field[arr[0]][0].message,
            druation: 1500
          })
        }
        console.log('验证通过');
        const { data: res } = await tabUpdateApi({
          labelCateId: this.editTabForm.labelCateId, labelName: this.editTabForm.labelName, labelSort: this.editTabForm.labelSort, labelColor: this.editTabForm.labelColor,  notes: this.editTabForm.notes
        });
        console.log("编辑成功");
        this.editTabDialogVisible = false;
        this.getTabList();
      })
    },

    //todo 删除分类
    async removeTabByID(cateInfo) {
      let result = await this.$confirm(`确定要删除该条记录？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).catch(reason => reason)

      // 取消删除
      if (result === 'cancel') {
        return this.$message.info({
          message: "已取消删除!",
          druation: 1500
        })
      }

      try {
        const { data: res } = await tabDeleteByIDApi({ labelCateId: cateInfo.labelCateId })
        this.$message.success({
          message: '删除成功!',
          druation: 1000
        })
        this.getTabList()
      } catch (error) {
        if (error.response.data.code == 100) {
          return this.$message.error({
            message: error.response.data.tip,
            druation: 1500
          })
        }
      }
    }
  }
}
</script>


<style lang="less" scoped>
.tabLibrary-container {
  padding: 15px;
}

//todo 搜索区域
.el-header {
  padding: 0 40px;
  background-color: #fff;

  .tabLibrary-search {
    display: flex;
    align-items: center;
    height: 60px;
  }

  .el-input {
    width: 300px;
  }
}

//todo 列表区域
.el-main {
  overflow: hidden !important;
  margin-top: 15px;
  background-color: #fff;
}
.el-button--mini {
  padding: 7px 3px;
  font-size: 10px;
}

//todo 新增对话框
.el-form {
  padding: 0 10px;
  
  .el-select,
  .el-input {
    width: 80%;
  }
}
</style>